<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- <form action="" method="post" enctype="application/x-www-form-urlencoded"></form> -->

    <button>点击我发送post方法的ajax请求</button>

    <script>
      let btn = document.querySelector("button");
      btn.onclick = function () {
        let xhr = new XMLHttpRequest();
        //方式是post
        xhr.open("post", "/getdata");
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              console.log(xhr.responseText);
            }
          }
        };

        //1.默认返送post数据  text/plan文本形式直接返送
        //2.设置form表单格式  请求头部的content-type需要和form表单的enctype一致
        //3.发送json数据  请求头部的content-type需要设置成application/json  数据需要发送json数据

        //设置请求头部:
        // xhr.setRequestHeader(
        //   "Content-Type",
        //   "application/x-www-form-urlencoded"
        // );
        xhr.setRequestHeader("Content-Type", "application/json");
        //post通过send发送数据  发送的格式是queryString

        // let data = "name=张三&age=20";
        let data = JSON.stringify({ myname: "hello", age: 20 });
        xhr.send(data);
      };
    </script>
  </body>
</html>
